<template>
  <div class="pd15">
    <a-modal v-model="showAddFilterDialog" title="新增过滤器" @ok="saveFilter">
      <ZgInput v-model="filterName" placeholder="请输入过滤器名称"></ZgInput>
    </a-modal>
    <a-form v-if="obj !== null" :labelCol="{ span: labelCol }" :wrapperCol="{ span: 24 - labelCol }">
      <a-row>
        <a-col v-for="(c, i) in conditions" :key="`condition${i}`" :span="columnCol">
          <a-form-item :label="c.label" style="margin-bottom: 0">
            <ZgDatePicker v-if="['日期', '日期时间'].includes(c.compType)" v-model="obj[c.code]"></ZgDatePicker>
            <ZgNumber v-else-if="['整数', '浮点数'].includes(c.compType)" v-model="obj[c.code]"></ZgNumber>
            <ZgDictionary
              v-else-if="['字典', '多选'].includes(c.compType)"
              :code="c.extra.字典类型"
              v-model="obj[c.code]"
            ></ZgDictionary>
            <ZgSelect
              v-else-if="c.compType === '下拉选择'"
              :options="c.extra.下拉选项"
              v-model="obj[c.code]"
            ></ZgSelect>
            <ZgSelect
              v-else-if="['单选框', '开关'].includes(c.compType)"
              :options="[
                { value: 'true', label: '是' },
                { value: 'false', label: '否' }
              ]"
              v-model="obj[c.code]"
            ></ZgSelect>
            <ZgInput v-else :placeholder="(c.extra && c.extra.placeholder) || ''" v-model="obj[c.code]"></ZgInput>
          </a-form-item>
        </a-col>
        <a-col :span="6" v-if="showInlineBtn">
          <div class="flx-s pt4 ml15">
            <ZgButton @click="reset" type="default" class="mr10" icon="refresh">重置</ZgButton>
            <ZgButton @click="searchWithCondition" icon="search">查询</ZgButton>
            <ZgButton
              class="ml10"
              :type="btn.type"
              :icon="btn.icon"
              @click="extraBtnClick(btn)"
              v-for="btn in extraBtns"
              :key="`btn${btn.key}`"
            >
              {{ btn.name }}
            </ZgButton>
          </div>
        </a-col>
      </a-row>
    </a-form>
    <div class="mt10">
      <a-row>
        <a-col :span="12">
          <ZgButton
            class="mr10"
            :type="btn.type"
            :icon="btn.icon"
            @click="extraBtnClick(btn)"
            v-for="btn in extraBtns"
            :key="`btn${btn.key}`"
          >
            {{ btn.name }}
          </ZgButton>
        </a-col>
        <a-col :span="12">
          <div class="flx-e">
            <ZgDropdown
              v-if="showFilterAdminBtn"
              @click="onClickFilterBtn"
              type="link"
              class="mr10"
              :opts="[
                { key: 1, label: '存为新的过滤器' },
                { key: 2, label: '更新过滤器' },
                { key: 3, label: '删除过滤器' }
              ]"
            >
              管理过滤器<i class="fa fa-ellipsis-h ml5" />
            </ZgDropdown>
            <ZgButton v-if="!showInlineBtn" @click="reset" type="default" class="mr10" icon="refresh">重置</ZgButton>
            <ZgButton v-if="!showInlineBtn" @click="searchWithCondition" icon="search">查询</ZgButton>
          </div>
        </a-col>
      </a-row>
    </div>
  </div>
</template>
<script>
import { pageMixin } from '@/core/page-mixin'

export default {
  mixins: [pageMixin],
  props: {
    uniqueName: {
      type: String,
      default: 'test'
    },
    labelCol: {
      type: Number,
      default: 6
    },
    columnCol: {
      type: Number,
      default: 6
    },
    currFilterName: {
      type: String,
      default: ''
    },
    showFilterAdminBtn: {
      type: Boolean,
      default: false
    },
    showInlineBtn: {
      type: Boolean,
      default: true
    },
    extraBtns: {
      type: Array,
      default: () => {
        return []
      }
    },
    conditions: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      obj: null,
      defaultObj: null, // 保存初始化默认值
      showAddFilterDialog: false,
      filterName: ''
    }
  },
  mounted() {
    this.initData()
    this.calculateHeight()
  },
  watch: {
    conditions: {
      handler(newVal, oldVal) {
        this.initData()
        this.calculateHeight()
      },
      deep: true // 开启深度监听，确保可以监听到嵌套属性的变化
    }
  },
  methods: {
    calculateHeight() {
      this.$emit(
        'height',
        (this.showInlineBtn ? 30 : 70) +
          Math.ceil((this.conditions.length + (this.showInlineBtn ? 1 : 0)) / (24 / this.columnCol)) * 40
      )
    },
    getCondition() {
      return JSON.stringify(this.obj)
    },
    set(t) {
      this.obj = Object.assign({}, this.defaultObj, JSON.parse(t))
    },
    reset() {
      // 所有参数设置默认值
      this.obj = Object.assign({}, this.defaultObj)
    },
    searchWithCondition() {
      // 查询参数
      this.$emit('search', this.getCondition())
    },
    saveFilter() {
      // 保存过滤器
      if (!this.filterName || this.filterName.length === 0) {
        this.$error({ title: '请输入过滤器名称！' })
        return
      }
      const condition = this.getCondition()
      const key = this.currentUser.username + '_diyFilter_' + this.uniqueName
      const diyFilters = localStorage.getItem(key)
      if (!diyFilters) {
        localStorage.setItem(
          key,
          JSON.stringify([
            {
              name: this.filterName,
              count: 0,
              condition: condition
            }
          ])
        )
      } else {
        const arr = JSON.parse(diyFilters)
        if (
          arr.some((t) => {
            return t.name === this.filterName
          })
        ) {
          this.$error({ title: '过滤器名称已经被使用！' })
          return
        }
        arr.unshift({
          name: this.filterName,
          count: 0,
          condition: condition
        })
        localStorage.setItem(key, JSON.stringify(arr))
      }
      this.showAddFilterDialog = false
      this.$success({ title: '操作成功！' })
      this.$emit('refresh', true)
    },
    onRangeChange(v, code) {
      this.obj[code + '_s'] = v[0]
      this.obj[code + '_e'] = v[1]
    },
    initData() {
      const json = {}
      this.conditions.forEach((c) => {
        json[c.code] = c.defaultVal
      })
      this.obj = json
      this.defaultObj = JSON.parse(JSON.stringify(json))
    },
    onClickFilterBtn(t) {
      if (t.key === 1) {
        this.filterName = ''
        this.showAddFilterDialog = true
      } else if (t.key === 2) {
        // 更新过滤器
        const key = this.currentUser.username + '_diyFilter_' + this.uniqueName
        const diyFilters = localStorage.getItem(key)
        if (!diyFilters) {
          this.$error({ title: '没有过滤器！' })
          return
        }
        if (diyFilters) {
          const arr = JSON.parse(diyFilters)
          if (
            !arr.some((t) => {
              return t.name === this.currFilterName
            })
          ) {
            this.$error({ title: '没有此过滤器！' })
            return
          }
          const newArr = arr.map((t) => {
            if (t.name === this.currFilterName) {
              t.condition = this.getCondition()
            }
            return t
          })
          localStorage.setItem(key, JSON.stringify(newArr))
          this.$success({ title: '操作成功' })
          this.$emit('refresh', false)
        }
      } else if (t.key === 3) {
        // 删除过滤器
        const key = this.currentUser.username + '_diyFilter_' + this.uniqueName
        const diyFilters = localStorage.getItem(key)
        if (!diyFilters) {
          this.$error({ title: '没有过滤器！' })
          return
        }
        if (diyFilters) {
          const arr = JSON.parse(diyFilters)
          if (
            !arr.some((t) => {
              return t.name === this.currFilterName
            })
          ) {
            this.$error({ title: '没有此过滤器！' })
            return
          }
          const newArr = arr.filter((t) => {
            return t.name !== this.currFilterName
          })
          if (newArr.length === 0) {
            localStorage.removeItem(key)
          } else {
            localStorage.setItem(key, JSON.stringify(newArr))
          }
          this.$success({ title: '操作成功' })
          this.$emit('refresh', true)
        }
      }
    },
    extraBtnClick(btn) {
      this.$emit('extraBtnClick', btn.key)
    }
  }
}
</script>

<style lang="scss" scoped></style>
